package com.mesSystem.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mesSystem.dto.ProcessRouteRequst;
import com.mesSystem.dto.Result;
import com.mesSystem.entity.Employee;
import com.mesSystem.entity.ProcessRoute;
import com.mesSystem.entity.WorkstationAndEmployee;
import com.mesSystem.service.impl.ProcessRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@ResponseBody
@Slf4j
@RequestMapping("processRoute")
public class ProcessRouteController {

    @Autowired
    ProcessRouteService processRouteService;

    @PostMapping("increase")
    public Result increase(@RequestBody ProcessRouteRequst requst) {
        ProcessRoute processRoute = requst.getProcessRoute();
        List<Long> processList = requst.getProcessList();
        String strList = JSONUtil.toJsonStr(processList);
        processRoute.setProcessList(strList);
        processRouteService.save(processRoute);
        return Result.ok("更新成功");
    }

    @PostMapping("update")
    public Result update(@RequestBody ProcessRouteRequst requst) {
        // 获取传更新信息
        ProcessRoute processRoute = requst.getProcessRoute();
        // 获取根据id数据库中的工艺的工序,并转为list
        String sqlProcessListJson = processRouteService
                .getById(processRoute.getProcessRouteId())
                .getProcessList();
        List<Long> sqlProcessList = JSONUtil.toList(sqlProcessListJson, Long.class);

        // 获取更新信息
        List<Long> processList = requst.getProcessList();

        // 循环遍历，若工艺中有该工序则剔除，若没有则添加
        for(Long process : processList) {
            if (processList.contains(process)) {
                processList.remove(process);
            } else {
                processList.add(process);
            }
        }

        String strList = JSONUtil.toJsonStr(processList);
        processRoute.setProcessList(strList);
        processRouteService.updateById(processRoute);
        return Result.ok("更新成功");
    }

    @DeleteMapping("delete")
    public Result delete(Long processRouteId) {
        processRouteService.removeById(processRouteId);
        return Result.ok("删除成功");
    }

    @GetMapping("query")
    public Result query(@RequestParam(value = "page", defaultValue = "1") Integer page,
                        @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<ProcessRoute> processRoutePage = new Page<>(page,size);
        processRouteService.page(processRoutePage,
                new QueryWrapper<ProcessRoute>().orderByDesc("name"));
        List<ProcessRoute> processRouteList = processRoutePage.getRecords();
        return Result.ok(processRouteList);
    }

}
